<template>
  <div class="userPermiss">
    <a-card :bordered="false" title="用户列表">
      <div slot="extra">
        <a-input-search style="margin-left: 16px; width: 272px;" @search="onSearch" />
      </div>
      <a-table
        :pagination="pagination"
        :rowKey="loadData=>loadData.userId"
        :columns="columns"
        :dataSource="loadData"
        :loading="loading"
        @change="handleTableChange"
      >

        <span slot="roleList" slot-scope="row">
          <p>{{ row }}</p>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="doAdd(record)">编辑</a>
        </span>
      </a-table>

      <!-- <role-modal ref="modal" @ok="handleOk"></role-modal> -->
      <!-- 新增弹窗 -->
      <a-modal
        title="设置角色"
        :visible="visible2"
        @ok="handleOk2"
        :width="600"
        :height="300"
        :centered="true"
        @cancel="handleCancel2"
      >
        <a-card title class="card" :bordered="false">
          <div style="margin-bottom: 16px">
            <a-row :gutter="24">
              <a-col :lg="24" :md="24" :sm="24">
                <div
                  style="display: flex;justify-content: space-between;align-items: center;margin-top:10px"
                >
                  <span style="width:100px;">角色:</span>
                  <a-select
                    mode="multiple"
                    style="width: 100%"
                    :value="roleCodeList"
                    @change="handleChange"
                    placeholder="请选择角色!"
                    allowClear>
                    <a-select-option v-for="(item, index) in rolesList" :key="index" :value="item.rlUniCode">{{ item.rlName }}</a-select-option>
                  </a-select>
                </div>
              </a-col>

            </a-row>
          </div>
        </a-card>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { getUserRole, doAddUser, getRoleList } from '@/api/admin/permission'

export default {
  name: 'UserPermiss',
  data () {
    return {
      description: '',
      pagination: {
        pageSize: 15,
        page: 1
      },
      visible: false,
      visible2: false,
      loading: false,
      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: 'ID',
          dataIndex: 'userId'
        },
        {
          title: '用户名称',
          dataIndex: 'user'
        },
        {
          title: '用户身份',
          dataIndex: 'roleList',
          scopedSlots: { customRender: 'roleList' }
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadData: [],
      rolesList: [],
      selectedRowKeys: [],
      selectedRows: [],
      roleCodeList: [],
      roleList: [],
      userId: '',
      userName: ''
    }
  },
  created () {
    this.getUserRole(15, 1)
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      // console.log(pagination)
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      if (this.userName !== '') {
        this.getUserRole(this.pagination.pageSize, this.pagination.current, this.userName)
      } else {
        this.getUserRole(this.pagination.pageSize, this.pagination.current, '')
      }
      // this.getUserList()
    },
    onSearch (value) {
      this.userName = value
      this.getUserRole(15, 1, value)
    },
    handleChange (value) {
      // console.log(`selected ${value}`)
      this.roleCodeList = value
      // console.log(`this.roleCodeList`, this.roleCodeList)
    },
    handleOk2 (e) {
      if (this.userId !== '') {
        if (this.roleCodeList !== []) {
          this.visible2 = false
          // this.confirmLoading = false
          this.doAddUser(this.userId, this.roleCodeList)
        }
      } else {
        this.$message.info('请填写ID或角色!')
      }
    },
    handleCancel2 (e) {
      this.visible2 = false
      // console.log('Clicked cancel button')
    },
    eval (fn) {
      // 数组字符串转数组
      var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
      return new Fn('return ' + fn)()
    },
    doAdd (record) {
      this.visible2 = true
      if (record) {
        this.userId = record.userId
        // console.log('record.roleCodeList', record.roleCodeList)
        this.roleCodeList = this.eval(record.roleCodeList)
      }
    },
    getRoleList () {
      getRoleList().then((res) => {
        // console.log('角色列表', res.result.role)
        this.rolesList = res.result.role
          // console.log('this.loadData', this.loadData)
        for (var i = 0; i < this.loadData.length; i++) {
          this.roleList = []
          // console.log('00')
          var arr = this.eval(this.loadData[i].roleCodeList)
          // console.log('arr', arr)
          var arr2 = []
            // var arr2 = []
          if (arr !== null) {
            for (var j = 0; j < arr.length; j++) {
              arr2.push(...this.rolesList.filter(e => e.rlUniCode === arr[j]))
            }
            // console.log('arr2', arr2)
            this.roleList.push(...arr2.map(e => { return e.rlName }))
            // console.log('this.rolesList', this.rolesList)
            this.roleList=this.roleList.toString()
            this.loadData[i].roleList=this.roleList
            // console.log('00', this.loadData)
            }
          }
        // }
      }).catch(err => {
        console.log(err)
      })
    },
    doAddUser (id, roleList) {
      doAddUser(
        {
          userId: id,
          roleCodeList: JSON.stringify(roleList)
        }
      ).then(res => {
        //console.log(res)
        this.$message.success('操作成功!')
        this.getUserRole(15, 1)
      }).catch(err => {
        console.log(err)
      })
    },
    getUserRole (pageSize, page, name) {
      this.loading = true
      getUserRole({
        pageSize: pageSize,
        page: page,
        userName: name === '' ? undefined : name
      }).then(res => {
        this.getRoleList()
        //console.log('用户列表', res.result)
        const pagination = { ...this.pagination }
        pagination.total = res.result.total
        this.pagination = pagination
        this.loadData = res.result.data
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>

</style>
